package vn.edu.saigontech.ncms.service.impl;

import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;

import vn.edu.saigontech.ncms.model.comparator.DayOffComparator;
import vn.edu.saigontech.ncms.model.system.DayOff;
import vn.edu.saigontech.ncms.service.DayOffService;
import vn.edu.saigontech.ncms.util.DateUtil;

@SuppressWarnings("unchecked")
public class DayOffServiceImpl extends HibernateGenericService<DayOff, Long>
		implements DayOffService {

	@Override
	public boolean exists(Date date) {
		return this.findByDate(date) != null;
	}

	@Override
	public Collection<DayOff> findAll() {
		Criteria criteria = this.createCriteria();
		List<DayOff> list = criteria.list();
		Collections.sort(list, new DayOffComparator());
		return list;
	}

	@Override
	public DayOff findByDate(Date date) {
		Criteria criteria = this.createCriteria();
		List dayOffs = criteria.list();
		for (int i = 0; i < dayOffs.size(); i++) {
			DayOff dayOff = (DayOff) dayOffs.get(i);
			List<Date> dates = DateUtil.sequenceAsList(dayOff.getDate(), dayOff
					.getEndDate());
			if (DateUtil.contains(dates, date, dayOff.isYearlyRepeat())) {
				return dayOff;
			}
		}
		return null;
	}
}